﻿using System;
using System.Web;
using System.IO;
using System.Web.SessionState;

namespace SharingCenter.Web.Services
{
    using SharingCenter.Web.Classes;
    using System.Drawing;
    using System.Drawing.Imaging;
    using SharingCenter.Web.Classes.Albums;
    public class UploadFileHandler : IHttpHandler, IRequiresSessionState
    {
        

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";   

            try
            {
                HttpPostedFile file = context.Request.Files["Filedata"];

                Guid userId = new Guid(context.Request["userid"]);
                Guid albumId = new Guid(context.Request["albumid"]);
                string albumFolder = "/Content/Albums/" + context.Request["albumid"];
                string serverAlbumFolder = context.Server.MapPath("~" + albumFolder);
                string serverAlbumThumbFolder = serverAlbumFolder + "/thumb";
                string serverAlbumMediumFolder = serverAlbumFolder + "/m";

                if (!Directory.Exists(serverAlbumFolder))
                {
                    Directory.CreateDirectory(serverAlbumFolder);
                }

                if (!Directory.Exists(serverAlbumThumbFolder))
                {
                    Directory.CreateDirectory(serverAlbumThumbFolder);
                }

                if (!Directory.Exists(serverAlbumMediumFolder))
                {
                    Directory.CreateDirectory(serverAlbumMediumFolder);
                }

                //string newFileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                string newFileName = file.FileName;
                file.SaveAs(string.Format(@"{0}\{1}", serverAlbumFolder, newFileName));
                Bitmap resized;
                Utility.ImageUtility.ResizeImage(150, file.InputStream, out resized);
                resized.Save(string.Format(@"{0}\{1}", serverAlbumThumbFolder, newFileName), resized.RawFormat);

                Utility.ImageUtility.ResizeImageByWidthOnly(700, file.InputStream, out resized);
                resized.Save(string.Format(@"{0}\{1}", serverAlbumMediumFolder, newFileName), resized.RawFormat);

                // insert database
                AlbumOperations.AddImage(newFileName, albumId, userId, true);
                //resized.Save(string.Format(@"{0}\{1}", serverAlbumFolder, "cover.jpg"), ImageFormat.Jpeg);

                context.Response.Write(albumFolder + "/" + newFileName);
            }
            catch(Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}